package com.baidu.iit.pxp.el.juel;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * User: huangweili
 * Date: 14-4-29
 * Time: 下午3:21
 */
public final class Cache implements TreeCache {
    private final Map<String,Tree> primary;
    private final Map<String,Tree> secondary;


    public Cache(int size) {
        this(size, new WeakHashMap<String,Tree>());
    }

    @SuppressWarnings("serial")
    public Cache(final int size, Map<String,Tree> secondary) {
        this.primary = Collections.synchronizedMap(new LinkedHashMap<String, Tree>(16, 0.75f, true) {
            @Override
            protected boolean removeEldestEntry(Map.Entry<String, Tree> eldest) {
                if (size() > size) {
                    if (Cache.this.secondary != null) {
                        Cache.this.secondary.put(eldest.getKey(), eldest.getValue());
                    }
                    return true;
                }
                return false;
            }
        });
        this.secondary = secondary == null ? null : Collections.synchronizedMap(secondary);
    }

    public Tree get(String expression) {
        if (secondary == null) {
            return primary.get(expression);
        } else {
            Tree tree = primary.get(expression);
            if (tree == null) {
                tree = secondary.get(expression);
            }
            return tree;
        }
    }

    public void put(String expression, Tree tree) {
        primary.put(expression, tree);
    }
}
